package legend.config;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import org.apache.shardingsphere.driver.api.yaml.YamlShardingSphereDataSourceFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.sql.SQLException;

/**
 * @author JNPF开发平台组
 * @user N
 * @copyright 引迈信息技术有限公司
 * @date 2022/11/23 16:52
 */
@Configuration
@ConditionalOnMissingClass( "org.springframework.cloud.loadbalancer.annotation.LoadBalancerClient")
@ConditionalOnProperty(prefix = "config", name = "sharding-sphere-enabled", havingValue = "true")
public class ShardingSphereAutoConfig {

    public ShardingSphereAutoConfig() {
        System.out.println("启用ShardingSphere");
    }

    public static final String PREFIX = "shardingsphere";

    @Bean
    public Object initShardingSphereDataSource(@Qualifier("dataSourceSystem") DynamicRoutingDataSource dataSource) throws SQLException, IOException, URISyntaxException {
        // 加入ShardingSphere数据源
        File file = new File(ShardingSphereAutoConfig.class.getClassLoader().getResource("sharding-sphere.yml").toURI());
        DataSource SSDataSource = YamlShardingSphereDataSourceFactory.createDataSource(file);
        dataSource.addDataSource(PREFIX, SSDataSource);
        return null;
    }



}
